package top.drinyeit.nongmao.presenter;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.scu.miomin.shswiperefresh.core.SHSwipeRefreshLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.drinyeit.nongmao.R;
import top.drinyeit.nongmao.activity.CommodityDetailNewActivity;
import top.drinyeit.nongmao.activity.ConfirmOrderActivity;
import top.drinyeit.nongmao.activity.ShopInnerGoodsActivity;
import top.drinyeit.nongmao.adapter.CategoryAdapter;
import top.drinyeit.nongmao.adapter.CategoryCartAdapter;
import top.drinyeit.nongmao.adapter.GroupAdapter;
import top.drinyeit.nongmao.app.Constant;
import top.drinyeit.nongmao.app.MyApplication;
import top.drinyeit.nongmao.model.CartListBean;
import top.drinyeit.nongmao.model.CategoryBean;
import top.drinyeit.nongmao.model.CategoryGoodsDetailsBean;
import top.drinyeit.nongmao.model.ClassificationBean;
import top.drinyeit.nongmao.model.SecCategoryBean;
import top.drinyeit.nongmao.model.TemporaryOrderDetailBean;
import top.drinyeit.nongmao.model.param.CartParam;
import top.drinyeit.nongmao.retrofit.HttpResponse;
import top.drinyeit.nongmao.retrofit.RetrofitMethod;
import top.drinyeit.nongmao.retrofit.subscriber.CommonSubscriber;
import top.drinyeit.nongmao.retrofit.subscriber.SubscriberListener;
import top.drinyeit.nongmao.util.SPUtil;

import static top.drinyeit.nongmao.app.Constant.COMMON_SUCCESS;

/**
 * Created by wu on 2018/1/27.
 * last update on 18/3/22
 */

public class ShopInnerGoodsPresenter {
    private ShopInnerGoodsActivity activity;
    int p, s, t;
    private CategoryAdapter categoryAdapter;
    private CategoryCartAdapter categoryCartAdapter;
    public List<CategoryBean> data;//分类数据
    public int type = 1;
    public static int priceNo = 0;
    public static int soldNo = 0;
    public int pageIndex;
    private GroupAdapter groupAdapter;
    private mHandler mHandler;

    public ShopInnerGoodsPresenter(ShopInnerGoodsActivity activity) {
        this.activity = activity;
        initListener();
        getCategory();
        getCla();
    }

    public void initListener() {
        activity.shSwipeRefreshLayout.setOnRefreshListener(new SHSwipeRefreshLayout.SHSOnRefreshListener() {
            @Override
            public void onRefresh() {
                Map<String, Object> map = new HashMap<>();
                map.put("type", type);
                map.put("action", "commodity_category_goods");
                map.put("category_id", activity.category_id);
                if (priceNo == 0 && soldNo != 0) {
                    map.put("sell_type", soldNo);
                } else if (priceNo != 0 && soldNo == 0) {
                    map.put("price_type", priceNo);
                }
                map.put("page_index", 1);
                categorySearch(map);
            }

            @Override
            public void onLoading() {
                Map<String, Object> map = new HashMap<>();
                map.put("type", type);
                map.put("action", "commodity_category_goods");
                map.put("category_id", activity.category_id);
                if (priceNo == 0 && soldNo != 0) {
                    map.put("sell_type", soldNo);
                } else if (priceNo != 0 && soldNo == 0) {
                    map.put("price_type", priceNo);
                }
                map.put("page_index", pageIndex + 1);
                categorySearch(map);
            }

            @Override
            public void onRefreshPulStateChange(float v, int i) {

            }

            @Override
            public void onLoadmorePullStateChange(float v, int i) {

            }
        });
//        activity.price_sort.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                priceSort();
//            }
//        });
//        activity.sold_sort.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                soldSort();
//            }
//        });
    }



    //获取商品列表
    public void categorySearch(Map<String, Object> map) {
        final int index = (int) map.get("page_index");
        final int priceType = map.get("price_type") == null ? 0 : (int) map.get("price_type");
        final int selxlType = map.get("sell_type") == null ? 0 : (int) map.get("sell_type");
        final int type = map.get("type") == null ? 0 : (int) map.get("type");
        t = type;
        p = priceType;
        s = selxlType;
        CommonSubscriber<HttpResponse<List<CategoryGoodsDetailsBean>>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<List<CategoryGoodsDetailsBean>>>() {
            @Override
            public void onError(String e, int code) {
                activity.shSwipeRefreshLayout.finishLoadmore();
                activity.shSwipeRefreshLayout.finishRefresh();
                activity.showToastMsg("错误，请重新操作!");
            }

            @Override
            public void onNext(final HttpResponse<List<CategoryGoodsDetailsBean>> o) {
                activity.shSwipeRefreshLayout.finishLoadmore();
                activity.shSwipeRefreshLayout.finishRefresh();
                if (o.getCode() == COMMON_SUCCESS) {
                    if (p != priceType || s != selxlType || t != type) {
                        categoryAdapter = new CategoryAdapter(o.getData(), activity.mHandler);
                    }
                    pageIndex = index;
                    if (index == 1) {
                        if (categoryAdapter == null) {
                            if (o.getData() != null && o.getData().size() > 0) {
                                categoryAdapter = new CategoryAdapter(o.getData(), activity.mHandler);
                                activity.mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
                                activity.mRecyclerView.setAdapter(categoryAdapter);
                            }
                        } else {
                            if (o.getData() == null || o.getData().size() == 0) {
                                categoryAdapter.clear();
                            } else {
                                categoryAdapter.setData(o.getData());
                            }
                            categoryAdapter.notifyDataSetChanged();
                        }
                    } else if (index > 1) {
                        if (o.getData() != null && o.getData().size() > 0) {
                            categoryAdapter.addData(o.getData());
                            categoryAdapter.notifyItemRangeInserted(categoryAdapter.getData().size(), o.getData().size());
                        } else {
                            activity.showToastMsg("没有更多啦");
                        }
                    }
                    if (categoryAdapter != null && categoryAdapter.getData().size() > 0) {
                        categoryAdapter.setOnItemClickListener(new CategoryAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, final int position) {
                                Intent intent = new Intent(activity, CommodityDetailNewActivity.class);
                                intent.putExtra("id", categoryAdapter.getData().get(position).getId());
                                activity.startActivityForResult(intent, 1);
                            }
                        });
                    }

                } else {
                    activity.showToastMsg(o.getMessage());
                }

            }
        });
        RetrofitMethod.getInstance().categorySearch(subscriber, map);
    }

    //获取购物车列表
    public void getCartList() {
        String user_id = SPUtil.getShareString(Constant.USER_ID);
        if (user_id.equals("")) {
            Toast.makeText(MyApplication.getInstance(), "请先登录", Toast.LENGTH_SHORT).show();
            activity.money.setText("总计: ¥0.00");
            activity.number.setText("共0件商品");
            activity.pay.setText("无商品");
            activity.goodsNumber.setVisibility(View.GONE);
            activity.pay.setBackgroundColor(ContextCompat.getColor(activity, R.color.hint_137));
            activity.pay.setClickable(false);
            return;
        }
        CommonSubscriber<HttpResponse<CartListBean>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<CartListBean>>() {
            @Override
            public void onError(String e, int code) {
                activity.shSwipeRefreshLayout.finishRefresh();
                Toast.makeText(MyApplication.getInstance(), "获取购物车列表失败", Toast.LENGTH_SHORT).show();
                activity.pay.setClickable(false);
            }

            @Override
            public void onNext(HttpResponse<CartListBean> o) {
                activity.shSwipeRefreshLayout.finishRefresh();
                if (o.getCode() == COMMON_SUCCESS) {
                    activity.pay.setClickable(true);
                    activity.pay.setText("去结算");
                    activity.pay.setBackgroundColor(ContextCompat.getColor(activity, R.color.app_green));
                    categoryCartAdapter = new CategoryCartAdapter(o.getData(), activity.mHandler);
                    activity.cartRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
                    activity.cartRecyclerView.setAdapter(categoryCartAdapter);
                    activity.money.setText("总计: ¥" + o.getData().getTotal_price() + "");
                    activity.number.setText("共" + o.getData().getTotal_sum() + "件商品");
                    activity.goodsNumber.setText("" + o.getData().getTotal_sum());
                    activity.goodsNumber.setVisibility(View.VISIBLE);
                    if (o.getData().getTotal_sum() == 0) {
                        activity.pay.setText("无商品");
                        activity.pay.setBackgroundColor(ContextCompat.getColor(activity, R.color.hint_137));
                        activity.goodsNumber.setVisibility(View.GONE);
                    }
                } else {
                    if (categoryCartAdapter != null) {
                        categoryCartAdapter.clear();
                    }
                    activity.pay.setClickable(false);
                    activity.money.setText("总计: ¥0.00");
                    activity.number.setText("共0件商品");
                    activity.pay.setText("无商品");
                    activity.goodsNumber.setVisibility(View.GONE);
                    activity.pay.setBackgroundColor(ContextCompat.getColor(activity, R.color.hint_137));
                    activity.pay.setClickable(false);
                }
            }
        });
        RetrofitMethod.getInstance().cartList(subscriber, user_id);
    }

    //删除全部商品
    public void deleteAll() {
        if (categoryCartAdapter == null) {
            activity.showToastMsg("您的购物车是空的");
            return;
        } else {
            if (categoryCartAdapter.getmData().size() == 0) {
                activity.showToastMsg("您的购物车是空的");
            }
        }

        final CommonSubscriber<HttpResponse<String>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<String>>() {
            @Override
            public void onError(String e, int code) {
                Toast.makeText(activity, "失败,请重新操作", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(HttpResponse<String> o) {
                if (o.getCode() == COMMON_SUCCESS) {
                    activity.pay.setText("无商品");
                    activity.pay.setBackgroundColor(ContextCompat.getColor(activity, R.color.hint_137));
                    activity.pay.setClickable(false);
                    categoryCartAdapter.clear();
                    categoryCartAdapter.notifyDataSetChanged();
                    activity.money.setText("总计: ¥0.00");
                    activity.number.setText("共0件商品");
                    activity.goodsNumber.setVisibility(View.GONE);
                } else {
                    if (categoryCartAdapter == null) {
                        activity.showToastMsg("您的购物车是空的");
                    } else {
                        if (categoryCartAdapter.getmData().size() == 0) {
                            activity.showToastMsg("您的购物车是空的");
                        } else {
                            Toast.makeText(activity, o.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

        });
        StringBuilder deleteGoodsIds = new StringBuilder();
        for (int i = 0; i < categoryCartAdapter.getmData().size(); i++) {
            deleteGoodsIds.append(categoryCartAdapter.getmData().get(i).getId());
            if (i < (categoryCartAdapter.getmData().size() - 1)) {
                deleteGoodsIds.append(",");
            }
        }
        RetrofitMethod.getInstance().deleteCart(subscriber, deleteGoodsIds.toString());
    }


    //去结算
    public void pay() {
        if (categoryCartAdapter == null) {
            activity.showToastMsg("");
        }
        List<CartParam.StoreParam> storeParamList = new ArrayList<>();
        for (int i = 0; i < categoryCartAdapter.getData().size(); i++) {
            List<CartParam.StoreParam.GoodsParam> goodsParamList = new ArrayList<>();
            for (int j = 0; j < categoryCartAdapter.getData().get(i).getCommodity_list().size(); j++) {
                CartParam.StoreParam.GoodsParam goodsParam = new CartParam.StoreParam.GoodsParam(categoryCartAdapter.getData().get(i).getCommodity_list().get(j).getId(),
                        categoryCartAdapter.getData().get(i).getCommodity_list().get(j).getCommodity_sum());
                goodsParamList.add(goodsParam);
            }
            CartParam.StoreParam storeParam = new CartParam.StoreParam(categoryCartAdapter.getData().get(i).getStore_id(), goodsParamList);
            storeParamList.add(storeParam);
        }
        CartParam cartParam = new CartParam(SPUtil.getShareString(Constant.USER_ID), storeParamList);
        CommonSubscriber<HttpResponse<TemporaryOrderDetailBean>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<TemporaryOrderDetailBean>>() {
            @Override
            public void onError(String e, int code) {
                activity.dismissLoading();
                Toast.makeText(MyApplication.getInstance(), "下单失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(HttpResponse<TemporaryOrderDetailBean> o) {
                activity.dismissLoading();
                if (o.getCode() == COMMON_SUCCESS) {
                    Intent intent = new Intent(activity, ConfirmOrderActivity.class);
                    intent.putExtra("temp_order", o.getData());
                    activity.startActivity(intent);
                } else {
                    Toast.makeText(MyApplication.getInstance(), o.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
        RetrofitMethod.getInstance().cartAccount(subscriber, new Gson().toJson(cartParam));
    }

    //获得所有分类
    public void getCla() {
        mHandler = new mHandler(activity);
        Map<String, Object> map = new HashMap<>();
        map.put("action", "commodity_category");
        CommonSubscriber<HttpResponse<ClassificationBean>> subscriber = new CommonSubscriber<>(new SubscriberListener<HttpResponse<ClassificationBean>>() {
            @Override
            public void onError(String e, int code) {
                activity.showToastMsg(e);
            }

            @Override
            public void onNext(final HttpResponse<ClassificationBean> o) {
                if (o.getCode() == COMMON_SUCCESS) {
                    data = myData(o.getData().getCategory());
                    if (groupAdapter == null && data.size() > 0){
                        groupAdapter = new GroupAdapter(data,mHandler,getNumber());
                    }
                    activity.groupRecycler.setLayoutManager(new LinearLayoutManager(activity));
                    activity.groupRecycler.setAdapter(groupAdapter);

                    getNumber();
                } else {
                    activity.showToastMsg(o.getMessage());
                }
            }
        });
        RetrofitMethod.getInstance().getCla(subscriber, map);
    }

    private List<CategoryBean> myData(List<CategoryBean> data) {
        SecCategoryBean secCategory;
        for (int i = 0; i < data.size(); i++) {
            secCategory = new SecCategoryBean();
            secCategory.setCategory_name("全部商品");
            secCategory.setId(data.get(i).getId());
            secCategory.setChecked_flag(0);
            data.get(i).getSec_categorys().add(0, secCategory);
        }
        return data;
    }

    static class mHandler extends Handler {
        private WeakReference<ShopInnerGoodsActivity> activityWeakReference;

        public mHandler(ShopInnerGoodsActivity activity) {
            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ShopInnerGoodsActivity activity = activityWeakReference.get();
            if (activity.isFinishing()) {
                return;
            }
            int type = 1;
            Map<String, Object> map;
            switch (msg.what) {
                case 0:
                    //父类点击
                    activity.category_id = activity.secondCategoryNewPresenter.data.get(msg.arg1).getId();
                    map = new HashMap<>();
                    map.put("type", type);
                    map.put("action", "commodity_category_goods");
                    map.put("category_id", activity.category_id);
                    if (ShopInnerGoodsPresenter.priceNo == 0 && soldNo != 0) {
                        map.put("sell_type", soldNo);
                    } else if (priceNo != 0 &&soldNo == 0) {
                        map.put("price_type", priceNo);
                    }
                    map.put("page_index", 1);
                    activity.secondCategoryNewPresenter.categorySearch(map);
                    activity.setTitle(true, activity.secondCategoryNewPresenter.data.get(msg.arg1).getCategory_name());
                    break;
                case 1:
                    //子类点击
                    if (msg.arg2 > 0) {
                        type = 2;
                        activity.category_id = activity.secondCategoryNewPresenter.data.get(msg.arg1).getSec_categorys().get(msg.arg2).getId();
                        activity.setTitle(true, activity.secondCategoryNewPresenter.data.get(msg.arg1).getCategory_name() + "-"
                        + activity.secondCategoryNewPresenter.data.get(msg.arg1).getSec_categorys().get(msg.arg2).getCategory_name());

                    }else {
                        type = 1;
                        activity.category_id = activity.secondCategoryNewPresenter.data.get(msg.arg1).getId();
                        activity.setTitle(true, activity.secondCategoryNewPresenter.data.get(msg.arg1).getCategory_name());

                    }
                    map = new HashMap<>();
                    map.put("type", type);
                    map.put("action", "commodity_category_goods");
                    map.put("category_id", activity.category_id);
                    if (priceNo == 0 && soldNo != 0) {
                        map.put("sell_type", soldNo);
                    } else if (priceNo != 0 && soldNo == 0) {
                        map.put("price_type", priceNo);
                    }
                    map.put("page_index", 1);
                    activity.secondCategoryNewPresenter.categorySearch(map);
                    break;

            }
        }
    }

    //判断哪个分类进入
    public int getNumber() {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getId() == activity.category_id) {
                data.get(i).setChecked_flag(1);
                return i;
            }
        }
        return 0;
    }

    private void getCategory() {
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("action", "commodity_category_goods");
        map.put("category_id", activity.category_id);
        map.put("page_index", 1);
        categorySearch(map);
    }

    //价格排序
    private void priceSort() {
//        activity.sold.setTextColor(ContextCompat.getColor(activity, R.color.text_black_51));
//        activity.sold.setCompoundDrawables(null, null, null, null);
        Map<String, Object> map = new HashMap<>();
        map.put("action", "commodity_category_goods");
        map.put("category_id", activity.category_id);
        Drawable drawable0 = ContextCompat.getDrawable(activity, R.drawable.up_arrow_icon);
        Drawable drawable1 = ContextCompat.getDrawable(activity, R.drawable.down_arrow_icon);
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
        drawable0.setBounds(0, 0, drawable0.getMinimumWidth(), drawable0.getMinimumHeight());
        if (priceNo == 0) {
            map.put("price_type", 1);
            map.put("page_index", 1);
            map.put("type", type);
            categorySearch(map);
//            activity.price.setTextColor(ContextCompat.getColor(activity, R.color.app_green));
//            activity.price.setCompoundDrawables(null, null, drawable0, null);
            priceNo = 1;
            soldNo = 0;
        } else if (priceNo == 1) {
            map.put("price_type", 2);
            map.put("page_index", 1);
            map.put("type", type);
            categorySearch(map);
//            activity.price.setCompoundDrawables(null, null, drawable1, null);
            priceNo = 2;
        } else {
            map.put("price_type", 1);
            map.put("page_index", 1);
            map.put("type", type);
            categorySearch(map);
//            activity.price.setCompoundDrawables(null, null, drawable0, null);
            priceNo = 1;
        }
    }

    //销量排序
    private void soldSort() {
//        activity.price.setTextColor(ContextCompat.getColor(activity, R.color.text_black_51));
//        activity.price.setCompoundDrawables(null, null, null, null);
        Map<String, Object> map = new HashMap<>();
        map.put("action", "commodity_category_goods");
        map.put("category_id", activity.category_id);
        Drawable drawable0 = ContextCompat.getDrawable(activity, R.drawable.up_arrow_icon);
        Drawable drawable1 = ContextCompat.getDrawable(activity, R.drawable.down_arrow_icon);
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
        drawable0.setBounds(0, 0, drawable0.getMinimumWidth(), drawable0.getMinimumHeight());
        if (soldNo == 0) {
            map.put("sell_type", 1);
            map.put("page_index", 1);
            map.put("type", type);
            categorySearch(map);
//            activity.sold.setTextColor(ContextCompat.getColor(activity, R.color.app_green));
//            activity.sold.setCompoundDrawables(null, null, drawable0, null);
            soldNo = 1;
            priceNo = 0;
        } else if (soldNo == 1) {
            map.put("sell_type", 2);
            map.put("page_index", 1);
            map.put("type", type);
            categorySearch(map);
//            activity.sold.setCompoundDrawables(null, null, drawable1, null);
            soldNo = 2;
        } else {
            map.put("sell_type", 1);
            map.put("page_index", 1);
            map.put("type", type);
            categorySearch(map);
//            activity.sold.setCompoundDrawables(null, null, drawable0, null);
            soldNo = 1;
        }
    }

}
